package org.jeecg.modules.achachievementsubject.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubject;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubjectDemo;
import org.jeecg.modules.achachievementsubject.service.IAchAchievementSubjectService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achachievementsubject.vo.AchAchievementSubjectVo;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecg.modules.common.utils.DateUtil;
import org.jeecg.modules.student.entity.StuStudentDemo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ach_achievement_subject
 * @author: baochangrong
 * @Date: 2022-03-18
 * @Version: V1.0
 */
@Api(tags = "ach_achievement_subject")
@RestController
@RequestMapping("/achachievementsubject/achAchievementSubject")
@Slf4j
public class AchAchievementSubjectController extends JeecgController<AchAchievementSubject, IAchAchievementSubjectService> {
    @Autowired
    private IAchAchievementSubjectService achAchievementSubjectService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param achAchievementSubject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-分页列表查询")
    @ApiOperation(value = "ach_achievement_subject-分页列表查询", notes = "ach_achievement_subject-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AchAchievementSubject achAchievementSubject,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AchAchievementSubject> queryWrapper = QueryGenerator.initQueryWrapper(achAchievementSubject, req.getParameterMap());
        Page<AchAchievementSubject> page = new Page<AchAchievementSubject>(pageNo, pageSize);
        IPage<AchAchievementSubject> pageList = achAchievementSubjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 科目成绩查询 分页
     */
    @AutoLog(value = "voList-分页列表查询")
    @ApiOperation(value = "voList-分页列表查询", notes = "voList-分页列表查询")
    @GetMapping(value = "/voList")
    public Result<?> voList(AchAchievementSubjectVo achAchievementSubjectVo,
                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                            HttpServletRequest req) {
        String tenantId = req.getHeader("tenant-id");
        achAchievementSubjectVo.setTenantId(tenantId);
        Page<AchAchievementSubjectVo> page = new Page<AchAchievementSubjectVo>(pageNo, pageSize);
        IPage<AchAchievementSubjectVo> pageList = achAchievementSubjectService.voList(page, achAchievementSubjectVo);
        return Result.OK(pageList);
    }


    /**
     * 查询导入批次号
     */
    @AutoLog(value = "listBatchNumber-查询导入批次号")
    @ApiOperation(value = "listBatchNumber-查询导入批次号", notes = "listBatchNumber-查询导入批次号")
    @GetMapping(value = "/listBatchNumber")
    public Result<?> voList(AchAchievementSubjectVo achAchievementSubjectVo,
                            HttpServletRequest req) {
        return achAchievementSubjectService.listBatchNumber(achAchievementSubjectVo);
    }


    /**
     * 添加
     *
     * @param achAchievementSubject
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-添加")
    @ApiOperation(value = "ach_achievement_subject-添加", notes = "ach_achievement_subject-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AchAchievementSubject achAchievementSubject, HttpServletRequest req) {
        String tenantId = req.getHeader("tenant-id");
        achAchievementSubject.setTenantId(tenantId);
        achAchievementSubjectService.save(achAchievementSubject);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param achAchievementSubject
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-编辑")
    @ApiOperation(value = "ach_achievement_subject-编辑", notes = "ach_achievement_subject-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AchAchievementSubject achAchievementSubject) {
        achAchievementSubjectService.updateById(achAchievementSubject);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-通过id删除")
    @ApiOperation(value = "ach_achievement_subject-通过id删除", notes = "ach_achievement_subject-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        achAchievementSubjectService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-批量删除")
    @ApiOperation(value = "ach_achievement_subject-批量删除", notes = "ach_achievement_subject-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.achAchievementSubjectService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_achievement_subject-通过id查询")
    @ApiOperation(value = "ach_achievement_subject-通过id查询", notes = "ach_achievement_subject-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AchAchievementSubject achAchievementSubject = achAchievementSubjectService.getById(id);
        if (achAchievementSubject == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(achAchievementSubject);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param achAchievementSubject
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchAchievementSubject achAchievementSubject) {
        return super.exportXls(request, achAchievementSubject, AchAchievementSubject.class, "ach_achievement_subject");
    }

    /**
     * 下载模板文件excel
     *
     * @param request
     * @param achAchievementSubjectDemo
     */
    @RequestMapping(value = "/exportXlsDemo")
    public ModelAndView exportXlsDemo(HttpServletRequest request, AchAchievementSubjectDemo achAchievementSubjectDemo) {


        //字典字段，字典编码请写入到这里
        JSONObject DictList = new JSONObject();
        DictList.put("成绩状态", "achievement_status");
        String secondTitle = "分数,考试日期为必填项，请严格按照要求填写。";
        return achAchievementSubjectService.exportXlsDemo(request, achAchievementSubjectDemo, "科目成绩导入", secondTitle, sysBaseAPI, DictList);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelDemo", method = RequestMethod.POST)
    public Result<?> importExcelDemo(HttpServletRequest request, HttpServletResponse response) {
        BaseApiEntity baseApiEntity = this.querySysInfo(request);
        return achAchievementSubjectService.importExcelDemo(request, response, achAchievementSubjectService, baseApiEntity);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchAchievementSubject.class);
    }

    /**
     * 从request获取 token 用户信息，组织信息
     *
     * @param req
     * @return
     */
    public BaseApiEntity querySysInfo(HttpServletRequest req) {

        BaseApiEntity baseApiEntity = new BaseApiEntity();

        //获取当前登录用户信息
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        baseApiEntity.setUsername(username);
        baseApiEntity.setCreateBy(username);
        baseApiEntity.setUpdateBy(username);

        LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
        baseApiEntity.setLoginUser(loginUser);
        String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换
        String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
        baseApiEntity.setTenantId(tenantId);

        String departId = sysBaseAPI.getDepartIdsByOrgCode(sysOrgCode);//获取当前用户设置的部门id
        List<String> subDepIdsList = sysBaseAPI.getSubDepIdsByDepId(departId); //获取下级部门的部门id，自定义改造sysBaseAPI
        baseApiEntity.setSysOrgCode(sysOrgCode);
        baseApiEntity.setSubDepIdsList(subDepIdsList);
        String subDepSysOrgCodes = sysBaseAPI.getSubDepOrgCodesByDepId(departId); //直接获取下级部门的orgcode，自定义改造sysBaseAPI
        baseApiEntity.setSubDepSysOrgCodes(subDepSysOrgCodes);
        //userIdentity 用户身份字典码user_identity， 3教师 4学生 1普通用户 2上级部门负责人 5家长 6班级
        int userIdentity = loginUser.getUserIdentity();//获取当前登录用户身份：字典码 user_identity
        baseApiEntity.setUserIdentity(userIdentity);

        return baseApiEntity;
    }

}
